package com.xoa.service.document;

import com.xoa.dao.document.DocumentStatisticsMapper;
import com.xoa.dao.workflow.FlowRunMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.dao.workflow.FlowSortMapper;
import com.xoa.dao.workflow.FlowTypeModelMapper;
import com.xoa.model.document.DocumentDispatchStatistics;
import com.xoa.model.document.DocumentShowModle;
import com.xoa.model.document.DocumentStatistics;
import com.xoa.model.document.DocumentStatusStatistics;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowDetailInfo;
import com.xoa.model.workflow.FlowSort;
import com.xoa.model.workflow.FlowTypeModel;
import com.xoa.service.workflow.JobClassifyService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.common.wrapper.BaseWrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pfl on 2017/7/26.
 */
@Service
public class DocumenSortFlowSerivce {
    @Resource
    private FlowTypeModelMapper flowTypeModelMapper;
    @Autowired
    JobClassifyService classifyService;
    @Autowired
    DocumentStatisticsMapper documentStatisticsMapper;

    @Autowired
    FlowSortMapper flowSortMapper;

    @Autowired
    FlowRunMapper flowRunMapper;
    @Autowired
    FlowRunPrcsMapper flowRunPrcsMapper;

    /**
     * 公文类型展示
     *
     * @param request
     * @param codeMainId
     * @param codeDetailId
     * @return
     */
    public BaseWrappers sortFlow(HttpServletRequest request, String codeMainId, String codeDetailId) {
        BaseWrappers toJson = new BaseWrappers();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        if (user.getUid() == null) {
            toJson.setFlag(false);
            toJson.setMsg("无法获取用户信息");
            return toJson;
        }
        if (codeMainId == null) {
            toJson.setFlag(false);
            toJson.setMsg("未知的公文类型");
            return toJson;
        }
        if (codeDetailId == null) {
            toJson.setFlag(false);
            toJson.setMsg("未知的发文类型");
            return toJson;
        }
        Map<String, Object> param = new HashMap<String, Object>();
        String privOther = user.getUserPrivOther() == null ? "" : user.getUserPrivOther();//辅助角色
        String privIds[] = StringUtils.checkNull(privOther) ? null : privOther.split(",");
        String deptOther = user.getDeptIdOther() == null ? "" : user.getDeptIdOther();//辅助部门
        String deptIds[] = StringUtils.checkNull(deptOther) ? null : deptOther.split(",");
        param.put("user", user.getUserId() == null ? "" : user.getUserId());
        param.put("deptId", user.getDeptId() == null ? "" : user.getDeptId());
        param.put("privId", user.getUserPriv() == null ? "" : user.getUserPriv());
        if (privIds != null && privIds.length > 0) {
            param.put("privIds", privIds);
        }
        if (deptIds != null && deptIds.length > 0) {
            param.put("deptIds", deptIds);
        }
        param.put("mainType", codeMainId);
        param.put("detailType", codeDetailId);
        List<FlowSort> sorts = flowSortMapper.documentFlowSortByAuth(param);
        StringBuffer sirtIdsTr = new StringBuffer();
        int i = 0;
        for (FlowSort sort : sorts) {
            sirtIdsTr.append(sort.getSortId());
            if (i != sorts.size()) {
                sirtIdsTr.append(",");
            }
            i++;
        }
        param.put("sortId", sirtIdsTr.toString());
        List<FlowTypeModel> flowTypeModels = flowTypeModelMapper.selectFlowAuthOrSearchByCodeId(param);
        List<DocumentShowModle> datas = factorDats(sorts, flowTypeModels);
        if (datas != null && datas.size() > 0) {
            toJson.setFlag(true);
            toJson.setMsg("成功");
            toJson.setDatas(datas);
        } else {
            toJson.setFlag(true);
            toJson.setMsg("失败");
        }
        return toJson;


    }

    /**
     * 数据组装
     *
     * @param sorts
     * @param flowTypeModels
     * @return
     */
    private List<DocumentShowModle> factorDats(List<FlowSort> sorts, List<FlowTypeModel> flowTypeModels) {
        List<DocumentShowModle> datas = new ArrayList<DocumentShowModle>();
        for (FlowSort sort : sorts) {
            DocumentShowModle showModle = new DocumentShowModle();
            showModle.setSortName(sort.getSortName());
            showModle.setSortId(sort.getSortId());
            showModle.setSortDetailId(sort.getSortDetailType());
            showModle.setSortMainId(sort.getSortMainType());
            List<FlowTypeModel> newDatas = new ArrayList<FlowTypeModel>();
            for (FlowTypeModel flowTypeModel : flowTypeModels) {
                if (flowTypeModel.getFlowSort().equals(sort.getSortId())) {
                    newDatas.add(flowTypeModel);
                }
            }
            showModle.setFlows(newDatas);
            datas.add(showModle);
        }
        return datas;
    }

    /**
     * 取消公文创建接口
     *
     * @param request
     * @param runId
     * @return
     */
    @Deprecated
    public BaseWrapper cancelDocument(HttpServletRequest request, Integer runId) {
        BaseWrapper wrapper = new BaseWrapper();
        wrapper.setStatus(true);
        if (runId == null) {
            wrapper.setFlag(false);
            wrapper.setMsg("清除数据失败");
            return wrapper;
        }
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        String userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId).getUserId();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", userId);
        param.put("runId", runId);
        //删除run表数据
        int a = flowRunMapper.cancelRun(param);
        int b = flowRunPrcsMapper.cancelRunPrcs(param);
        //删除runprcs表数据
        if (a > 0) {
            wrapper.setFlag(true);
            wrapper.setMsg("成功");
            return wrapper;
        }

        wrapper.setFlag(false);
        wrapper.setMsg("清除数据失败");
        return wrapper;
    }

    private final int STA_DIS = 0;//按文种排序
    private final int STA_STATUS = 2;//按类型排序

    /**
     * 获取公文统计数据（）
     *
     * @param request
     * @return
     */
    public BaseWrappers  getStatistics(HttpServletRequest request, Integer staType, String startTime, String endTime) {
        BaseWrappers wrapper = new BaseWrappers();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        switch (staType) {
            case STA_DIS:

                wrapper.setDatas(getDispatchData(param));
                break;
            case STA_STATUS:
                wrapper.setDatas(getStatusData(param));
                break;
        }
        wrapper.setMsg("ok");
        wrapper.setFlag(true);

        return wrapper;
    }

    //文种获取数据
    public List<DocumentDispatchStatistics> getDispatchData(Map<String, Object> param) {
        List<DocumentDispatchStatistics> dispatchData = documentStatisticsMapper.getDispatchStatistics(param);
        return dispatchData;
    }

    //获取状态数据
    public List<DocumentStatusStatistics> getStatusData(Map<String, Object> param) {
        List<DocumentStatusStatistics> dispatchData = documentStatisticsMapper.getStatusStatistics(param);
        return dispatchData;
    }

    public BaseWrappers getDocumentFlowType() {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        List<FlowDetailInfo> datas = flowTypeModelMapper.selectDocumentFloeType();
        wrappers.setDatas(datas);
        wrappers.setFlag(true);
        return wrappers;
    }

    /**
     * 常用公文
     *
     * @param request
     * @param codeMainId
     * @param codeDetailId
     * @return
     */
    public BaseWrappers sortCommonDocument(HttpServletRequest request, String codeMainId, String codeDetailId) {
        BaseWrappers toJson = new BaseWrappers();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        if (user.getUid() == null) {
            toJson.setFlag(false);
            toJson.setMsg("无法获取用户信息");
            return toJson;
        }
        if (codeMainId == null) {
            toJson.setFlag(false);
            toJson.setMsg("未知的公文类型");
            return toJson;
        }
        if (codeDetailId == null) {
            toJson.setFlag(false);
            toJson.setMsg("未知的发文类型");
            return toJson;
        }
        Map<String, Object> param = new HashMap<String, Object>();
        String privOther = user.getUserPrivOther() == null ? "" : user.getUserPrivOther();//辅助角色
        String privIds[] = StringUtils.checkNull(privOther) ? null : privOther.split(",");
        String deptOther = user.getDeptIdOther() == null ? "" : user.getDeptIdOther();//辅助部门
        String deptIds[] = StringUtils.checkNull(deptOther) ? null : deptOther.split(",");
        param.put("user", user.getUserId() == null ? "" : user.getUserId());
        param.put("deptId", user.getDeptId() == null ? "" : user.getDeptId());
        param.put("privId", user.getUserPriv() == null ? "" : user.getUserPriv());
        if (privIds != null && privIds.length > 0) {
            param.put("privIds", privIds);
        }
        if (deptIds != null && deptIds.length > 0) {
            param.put("deptIds", deptIds);
        }
        param.put("mainType", codeMainId);
        param.put("detailType", codeDetailId);
        List<FlowSort> sorts = flowSortMapper.documentFlowSortByAuth(param);
        StringBuffer sirtIdsTr = new StringBuffer();
        int i = 0;
        for (FlowSort sort : sorts) {
            sirtIdsTr.append(sort.getSortId());
            if (i != sorts.size()) {
                sirtIdsTr.append(",");
            }
            i++;
        }
        param.put("sortId", sirtIdsTr.toString());
        //根据权限查公文流程
        List<FlowTypeModel> flowTypeModels = flowTypeModelMapper.sortCommonDocument(param);
        StringBuffer str=new StringBuffer();
        for (FlowTypeModel flpwType:flowTypeModels
             ) {
            str.append(flpwType.getFlowId()+",");
        }
        //排序
        String[] flowIds = (str.toString()).split(",");
        List<Integer> paixu = flowRunMapper.sortFlowId(flowIds);
        List<FlowTypeModel> show=new ArrayList<>();
        for (Integer pai:paixu
             ) {
            show.add(flowTypeModelMapper.queryOneObject(pai));
        }
        if (show != null && show.size() > 0) {
            toJson.setFlag(true);
            toJson.setMsg("成功");
            toJson.setDatas(show);
        } else {
            toJson.setFlag(true);
            toJson.setMsg("失败");
        }
        return toJson;


    }
}
